package com.smart.opcda.service;

import com.smart.opcda.dto.Server;
import com.smart.opcda.topic.ServerManager;
import javafish.clients.opc.JEasyOpc;
import javafish.clients.opc.browser.JOpcBrowser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.DependsOn;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author dengqiao
 * @date 2024/3/19 14:08
 */
@DependsOn("serverManager")
@Slf4j
@Component
public class OpcDAManager {

    @Autowired
    private ServerManager serverManager;

    private Map<String, JEasyOpc> opcDAMap = new ConcurrentHashMap<>();

    @PostConstruct
    public void initOpc() {
        log.info("JOPC 开始初始化");
        JEasyOpc.coInitialize();
        browserServers();
        Map<String, Server> serverMap = serverManager.getServerMap();
        for (String serverId : serverMap.keySet()) {
            synchronized (this) {
                if (!opcDAMap.containsKey(serverId)) {
                    Server server= serverMap.get(serverId);
                    JEasyOpc jEasyOpc = new JEasyOpc("localhost", server.getServerName(), "JOPC" + opcDAMap.size());
                    jEasyOpc.start();
                    opcDAMap.put(serverId, jEasyOpc);
                }
            }
        }
    }

    public List<String> browserServers() {
        log.info("开始遍历所有的OPC DA Server");
        List<String> list = new ArrayList<>();
        try {
            String[] opcServers = JOpcBrowser.getOpcServers("localhost");
            log.info("-----[server]-----:");
            for (String server : opcServers) {
                log.info(server);
                list.add(server);
            }
            log.info("-----[server]-----:");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        log.info("OPC DA Server遍历完成");
        return list;
    }

    @PreDestroy
    private void coUninitialize() {
        log.info("JOPC 断开连接");
        JEasyOpc.coUninitialize();
    }

    public JEasyOpc getOpcInstance(String serverId) {
        if (opcDAMap.containsKey(serverId)) {
            JEasyOpc jEasyOpc = opcDAMap.get(serverId);
            if (jEasyOpc.ping()) {
                return jEasyOpc;
            }
        }
        return null;
    }
}
